#include "Manager.h"

// private
class CentersComp:public TrainingCompare
{
public:
	bool operator() (PUnitType& lhs, PUnitType& rhs)
	{
		// User specified priority is never ignored
		if(lhs.getPriority() != rhs.getPriority())
			return lhs.getPriority() > rhs.getPriority();

		// The rest occurs in the event of a tie
		return lhs.buildTime() <= rhs.buildTime();
	}
};

TrainingManager::TrainingManager(StratManager *newManager)
{
	manager = newManager;
	centers = new UnitGroup();
}

struct LeadTime TrainingManager::getUnitRequestTime(Request unitRequest)
{
	return manager->onUnitTimeQuerry(unitRequest);
}

void TrainingManager::onStart()
{
	supplyRequestSent = false;
}

void TrainingManager::onStop()
{
}

void TrainingManager::onTaskCompleted(UnitGroup* group)
{
	group->stop();
}

void TrainingManager::onThink()
{
	// Determine when to train a new unit
	centers->think();
}

void TrainingManager::onUnitRecieved(Unit *unit, bool requested)
{
	UnitType uType = unit->getType();
	// classify unit into a group
	if(!requested)
		if(Broodwar->self()->getRace().getCenter() == uType)
			centers->addUnit(unit);
}

// public
void TrainingManager::trainUnits(Request unitRequest)
{
	TrainAction<CentersComp> *trainAction = new TrainAction<CentersComp>();
	for(int i = 0; i < unitRequest.count; i++)
		trainAction->addUnitRequest(PUnitType(unitRequest.uType, unitRequest.group, unitRequest.priority));
	centers->addAction(trainAction, this, 0);
	delete trainAction;
}

TrainingManager::~TrainingManager()
{
	delete centers;
}